﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Linq;
using System.Linq;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using G.Net;
using G.Reader.API;

namespace G.Reader.Data
{
    public class BookDataBase : DataContext
    {
        private const string DBConnectionString_Books = "Data Source=isostore:/reader_books.sdf";

        public BookDataBase(string connectionstring)
            : base(connectionstring)
        {

        }
        #region 书本音频相关
        public void AddBookAudio(System.IO.Stream audioStream, BookAudio bookAudio)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string fileName = bookAudio.BookPath;
                byte[] buffer = audioStream.GetBytes();
                using (IsolatedStorageFileStream file = storage.CreateFile(fileName))
                {
                    file.Write(buffer);
                }
            }
            bookAudio.Size = audioStream.Length;
            this.BookAudiosTable.InsertOnSubmit(bookAudio);
            this.SubmitChanges();
        }
        #endregion

        #region 书本相关
        /// <summary>
        /// 删除书本，并且同时删除相关的音频文件
        /// </summary>
        /// <param name="book"></param>
        public void DeleteBook(BookInfo book)
        {
            using (var file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                foreach (var item in GloabalData.Instance.BookDataBase.BookAudiosTable.Where(c => c.BookId == book.ID))
                {
                    file.DeleteFile(item.BookPath);
                    GloabalData.Instance.BookDataBase.BookAudiosTable.DeleteOnSubmit(item);
                }
                this.BookTable.DeleteOnSubmit(book);
                this.SubmitChanges();
                file.DeleteFile(book.Path);
            }
        }
        /// <summary>
        /// 批量删除书本
        /// </summary>
        /// <param name="books"></param>
        public void DeleteBook(IEnumerable<BookInfo> books)
        {
            using (var file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                foreach (var book in books)
                {
                    file.DeleteFile(book.Path);
                }
            }
            this.BookTable.DeleteAllOnSubmit(books);
            this.SubmitChanges();
        }
        /// <summary>
        /// 读取书本内容
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        public string[] ReadBook(BookInfo book)
        {
            using (var file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var b = file.OpenFile(book.Path, System.IO.FileMode.Open))
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(b))
                    {
                        return GetStrs(reader).ToArray();
                    }
                }
            }
        }
        /// <summary>
        /// 获取书本的流
        /// </summary>
        /// <param name="book"></param>
        public System.IO.Stream GetBookStream(BookInfo book)
        {
            using (var file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var b = file.OpenFile(book.Path, System.IO.FileMode.Open))
                {
                    System.IO.Stream stream = new System.IO.MemoryStream();
                    b.CopyTo(stream);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);
                    return stream;
                }
            }
        }


        public void UpdateBookWithStream(System.IO.Stream buffer, BookInfo book)
        {
            AddBookToIsolatedStorage(buffer, book);
            book.Size = buffer.Length;
            this.SubmitChanges();
        }
    
        /// <summary>
        /// 读取全部的内容
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        public string ReadBookAll(BookInfo book)
        {
            using (var file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var b = file.OpenFile(book.Path, System.IO.FileMode.Open))
                {
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(b))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }

        private IEnumerable<string> GetStrs(System.IO.StreamReader reader)
        {
            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
            s.Start();
            do
            {
                string str = reader.ReadLine();

                if (str.Length > 1000)
                {
                    do
                    {
                        yield return str.Substring(0, 1000);
                        str = str.Substring(1000);
                    } while (str.Length > 1000);
                    yield return str;
                }
                else
                    yield return str;
            } while (!reader.EndOfStream);
            s.Stop();
        }
        /// <summary>
        /// 往数据库中添加书本
        /// </summary>
        /// <param name="bookStream"></param>
        /// <param name="book"></param>
        public void AddBook(System.IO.Stream buffer, BookInfo book)
        {
            book.Size = buffer.Length;
            this.BookTable.InsertOnSubmit(book);
            this.SubmitChanges();
            if (string.IsNullOrEmpty(book.BookName))
            {
                throw new InvalidOperationException("BookName不能为空，请设置书本的名称");
            }
            AddBookToIsolatedStorage(buffer, book);
        }
        /// <summary>
        /// 将书本保存到独立存储里面
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="book"></param>
        private static void AddBookToIsolatedStorage(System.IO.Stream buffer, BookInfo book)
        {
            using (var file = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!file.DirectoryExists("Books"))
                {
                    file.CreateDirectory("Books");
                }
                using (var bookFile = file.CreateFile(System.IO.Path.Combine("Books", string.Format("{0}.book", book.ID))))
                {
                    buffer.CopyTo(bookFile);
                }
            }
        }
        #endregion

        public static BookDataBase Create()
        {
            return new BookDataBase(DBConnectionString_Books);
        }

        public Table<BookInfo> BookTable;

        public Table<BookAudio> BookAudiosTable;
    }
}
